#! /bin/bash
echo "Hello This script is for install nginx, php and mysql on linux. "
echo "select your install program list."
echo "Default is php + nginx + mysql. enter 1 to install redis."
read -p "Your choice:" mode
echo "Default is /var/lib/mysql ."
read -p "MySQL data directory is:" dir
echo "Default is empty ."
read -p "MySQL root password:" pass

useradd www
sourceDir="/usr/local/src"

##
#
# update yum at first
#
##

yum -y install epel-release
yum update -y

##
#
# install desp
#
##
yum remove -y mysql*
echo "Install desp..."
yum install -y gcc gcc-c++ autoconf automake libtool re2c flex bison php-mcrypt libmcrypt libmcrypt-devel openssl-devel libxml2 libxml2-devel libcurl-devel libjpeg-devel libpng-devel freetype-devel zlib-devel mcrypt bzip2-devel libicu-devel systemd-devel mhash  glibc-devel glib2-devel ncurses-devel curl-devel gettext-devel libxslt-devel libxslt-dev pcre re2c wget

##
#
# install redis
#
##
if [ $mode = 1 ];then
    wget -O $sourceDir/redis-3.0.0.tar.gz http://download.redis.io/releases/redis-3.0.0.tar.gz
    tar -zxvf $sourceDir/redis-3.0.0.tar.gz -C $sourceDir
    cd $sourceDir/redis-3.0.0
    make
    #进入src目录
    mkdir /usr/local/redis
    cp $sourceDir/redis-3.0.0/src/redis-server  /usr/local/redis
    cp $sourceDir/redis-3.0.0/src/redis-benchmark /usr/local/redis
    cp $sourceDir/redis-3.0.0/src/redis-cli  /usr/local/redis
    touch /usr/local/redis/redis.conf
    #redis.conf配置文件
    cat  > /usr/local/redis/redis.conf <<EOF
pidfile /usr/local/redis/redis.pid
port 6379
tcp-backlog 511
daemonize yes
bind 127.0.0.1
timeout 0
tcp-keepalive 0
loglevel notice
logfile ""
databases 16
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir ./
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
EOF
    #redis 服务文件
    touch /usr/lib/systemd/system/redis.service
    chmod +x /usr/lib/systemd/system/redis.service
    cat >  /usr/lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/redis/redis.pid
ExecStart=/usr/local/redis/redis-server /usr/local/redis/redis.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable redis
    systemctl start redis
fi

##
#
# install mysql with yum 
#
##
wget -O $sourceDir/mysql57-community-release-el7-11.noarch.rpm https://repo.mysql.com//mysql57-community-release-el7-11.noarch.rpm
yum localinstall -y $sourceDir/mysql57-community-release-el7-11.noarch.rpm
yum install -y mysql-community-server
if [[  "$dir" ]];then
    if [[ ! -d $dir ]];then
        mkdir $dir
    fi
    dirSize=`ls -l $dir | egrep  -o "[0-9]+"`
    if [[ $dirSize = 0 ]]; then
        echo "start initialize in your direcotry"
        mysqld --initialize-insecure --user=mysql --datadir=$dir
        cp /etc/my.cnf /etc/my.cnf.bak
        cat  > /etc/my.cnf <<EOF
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
datadir=$dir
socket=$dir/mysql.sock

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
[mysql]
socket=$dir/mysql.sock
EOF
    else
        echo "your directory is not empty , so initialize default directory /var/lib/mysql."
        mysqld --initialize-insecure --user=mysql
    fi
else
    mysqld --initialize-insecure --user=mysql
fi
systemctl daemon-reload
systemctl enable mysqld.service
systemctl start mysqld
if [ ! "$pass" = "" ];then
    echo "set your root password..."
    mysql -u root -e "set password for 'root'@'localhost' = password('$pass');flush privileges;"
fi

##
#
# install php
#
##

wget -O $sourceDir/php7.tar.gz http://cn2.php.net/get/php-7.1.6.tar.gz/from/this/mirror
tar -zxvf $sourceDir/php7.tar.gz -C $sourceDir
cd $sourceDir/php-7.1.6

./configure --prefix=/usr/local/php  --with-curl  --with-freetype-dir --with-libdir=/usr/lib64 --with-png-dir=/usr/lib64 --with-gettext=/usr/lib64  --with-jpeg-dir --with-gd  --with-gettext  --with-iconv-dir  --with-kerberos  --with-libxml-dir  --with-mysqli  --with-openssl  --with-pcre-regex  --with-pdo-mysql  --with-pdo-sqlite  --with-pear  --with-png-dir  --with-xmlrpc  --with-xsl  --with-zlib  --enable-fpm  --enable-bcmath  --enable-libxml  --enable-inline-optimization  --enable-gd-native-ttf  --enable-mbregex  --enable-mbstring  --enable-opcache  --enable-pcntl  --enable-shmop  --enable-soap  --enable-sockets  --enable-sysvsem  --enable-xml  --with-libdir=lib64  --enable-zip --with-config-file-path=/usr/local/php/etc/ --with-fpm-user=php --with-fpm-group=www
if [ ! $? ];then
    echo 'PHP configure failed.'
	exit 3
fi


make && make install
if [ ! $? ];then
    echo 'PHP make failed.'
	exit 3
fi


##
#
# 复制相关文件
#
##
cp php.ini-development /usr/local/php/etc/php.ini
cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf
cp -R ./sapi/fpm/php-fpm /etc/init.d/php-fpm

cd ..

##
# 添加php-redis扩展
##

wget -O $sourceDir/phpredis-3.0.0.tar.gz https://github.com/phpredis/phpredis/archive/3.0.0.tar.gz
tar -zxvf $sourceDir/phpredis-3.0.0.tar.gz -C $sourceDir
cd $sourceDir/phpredis-3.0.0
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
result=`make && make install`
if [ !$? ];then
    echo "make php redis success."
    extDir=`echo $result | grep -o -P "/usr/local/php/lib/php/extensions/\S*"`
    extFile=${extDir}"redis.so"
    isAddPhpIni=`cat /usr/local/php/etc/php.ini | grep redis.so`
    if [[ -f $extFile ]] && [[ "$isAddPhpIni" = "" ]];then
        echo "extension=$extFile" >> /usr/local/php/etc/php.ini
    fi
else
    echo "make php redis failed."
fi
cd ..

##
# 添加swoole扩展
#
##
wget -O $sourceDir/swoole.tar.gz https://github.com/swoole/swoole-src/archive/v2.0.9.tar.gz
tar -zxvf $sourceDir/swoole.tar.gz  -C $sourceDir
cd $sourceDir/swoole-src-2.0.9/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
result=`make && make install`
if [ !$? ];then
    echo "make swoole success."
    extDir=`echo $result | grep -o -P "/usr/local/php/lib/php/extensions/\S*"`
    extFile=${extDir}"swoole.so"
    isAddPhpIni=`cat /usr/local/php/etc/php.ini | grep swoole.so`
    if [[ -f $extFile ]] && [[ "$isAddPhpIni" = "" ]];then
        echo "extension=$extFile" >> /usr/local/php/etc/php.ini
    fi
else
    echo "make swoole failed."
fi
cd ..

##
# 添加mongo扩展
#
##
wget -O $sourceDir/mongodb-1.2.10.tgz https://pecl.php.net/get/mongodb-1.2.10.tgz
tar -zxvf $sourceDir/mongodb-1.2.10.tgz  -C $sourceDir
cd $sourceDir/mongodb-1.2.10/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
result=`make && make install`
if [ !$? ];then
    echo "make php mongo success."
    extDir=`echo $result | grep -o -P "/usr/local/php/lib/php/extensions/\S*"`
    extFile=${extDir}"mongodb.so"
    isAddPhpIni=`cat /usr/local/php/etc/php.ini | grep mongodb.so`
    if [[ -f $extFile ]] && [[ "$isAddPhpIni" = "" ]];then
        echo "extension=$extFile" >> /usr/local/php/etc/php.ini
    fi
else
    echo "make mongo failed."
fi
cd ..

##
#
# 设置php-fpm.service文件
#
##
touch /lib/systemd/system/php-fpm.service
cat  > /lib/systemd/system/php-fpm.service <<EOF
[Unit]
Description=The PHP FastCGI Process Manager
After=network.target

[Service]
Type=forking
PIDFile=/run/php-fpm.pid
ExecStart=/usr/local/php/sbin/php-fpm --daemonize -g /run/php-fpm.pid --fpm-config /usr/local/php/etc/php-fpm.conf
ExecReload=/bin/kill -USR2 $MAINPID
ExecStop=/bin/kill -SIGINT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

chmod +x /lib/systemd/system/php-fpm.service
systemctl daemon-reload
systemctl enable php-fpm.service
systemctl start php-fpm.service


##
#
# 安装nginx
#
##
wget -O $sourceDir/nginx-1.10.0.tar.gz http://nginx.org/download/nginx-1.10.0.tar.gz
tar -zxvf $sourceDir/nginx-1.10.0.tar.gz -C $sourceDir
cd $sourceDir/nginx-1.10.0

./configure --sbin-path=/usr/local/nginx/nginx --conf-path=/usr/local/nginx/nginx.conf --pid-path=/usr/local/nginx/nginx.pid --with-http_ssl_module 
if [ ! $? ];then
    echo 'Nginx configure failed.'
	exit 3
fi


make && make install
if [ ! $? ];then
    echo 'Nginx make failed.'
	exit 3
fi
##
#
# 设置nginx.service文件
#
##
touch /lib/systemd/system/nginx.service
cat  > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx.service
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/nginx
ExecReload=/usr/local/nginx/nginx -s reload
ExecStop=/usr/local/nginx/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

mkdir /usr/local/nginx/vhost
cat  > /usr/local/nginx/nginx.conf <<EOF
user  nginx www;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        root html;
        location / {
        autoindex on;
            autoindex_exact_size off;
            autoindex_localtime on;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
        }
        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            try_files \$uri =404;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
            include        fastcgi_params;
        }
    }
    include vhost/*.conf;
}
EOF
touch /usr/local/nginx/html/info.php
echo -e "<?php phpinfo();" > /usr/local/nginx/html/info.php
chmod +x /lib/systemd/system/nginx.service

useradd -s /sbin/nologin -g www nginx
systemctl daemon-reload
systemctl enable nginx.service
systemctl start nginx.service

##
#
# 防火墙设置
#
##
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --permanent --add-port=9000/tcp
firewall-cmd --permanent --add-port=3306/tcp
firewall-cmd --permanent --add-port=6379/tcp

firewall-cmd --reload
